package com.my.blog.website.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.my.blog.website.dao.RechargeRecordVoMapper;
import com.my.blog.website.modal.Vo.RechargeRecordVo;
import com.my.blog.website.modal.Vo.RechargeRecordVoExample;
import com.my.blog.website.service.IAlipayService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @author ：gyh
 * @date ：Created in 2020/10/11 2:55
 * @description：阿里支付接口实现类
 * @modified By：gyh
 * @version: 1.0
 */
@Service
public class AlipayServiceImpl implements IAlipayService {
    private Logger logger = LoggerFactory.getLogger(getClass());


    @Resource
    private RechargeRecordVoMapper rechargeRecordMapper;

    public static final String PAY_SUCCESS = "TRADE_SUCCESS";

    /**
     * 查询订单支付状态并更新
     *
     * @param orderNo    订单号
     * @param appId
     * @param privateKey
     * @param publicKey
     * @return
     */
    @Override
    public boolean getPayState(String orderNo, String appId, String privateKey, String publicKey) throws AlipayApiException {
        logger.info(">>>>>>>>>>查询订单支付状态,orderNo=[" + orderNo + "]<<<<<<<<<<<");
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
                appId, privateKey, "json", "GBK", publicKey, "RSA2");
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        request.setBizContent("{" +
                "\"out_trade_no\":\"" + orderNo + "\"" +
                "  }");
        AlipayTradeQueryResponse response = alipayClient.execute(request);
        if (response != null && response.isSuccess() && PAY_SUCCESS.equals(response.getTradeStatus())) {
            //更新支付状态
            RechargeRecordVoExample example = new RechargeRecordVoExample();
            RechargeRecordVoExample.Criteria criteria = example.createCriteria();
            criteria.andOrderNoEqualTo(orderNo);
            RechargeRecordVo record = rechargeRecordMapper.selectByExample(example).stream().findFirst().orElse(null);
            if (record == null) {
                return false;
            }
            record.setStatus("1");
            record.setTradeTime(new Date());
            record.setTradeMoney(record.getRechargeMoney());
            rechargeRecordMapper.updateByPrimaryKeySelective(record);
            /**
             * 此处发送邮件通知用户支付成功
             */
            return true;
        } else {
            return false;
        }
    }

}
